<template>
  <div class="main">
    <div class="functionalArea">
      <el-button 
        v-for="item in functionalArea" 
        :key="item.name" 
        @click="showDialog(item.name)"
        size="large" 
        icon="CirclePlus" 
        type="primary">
        {{ item.name }}
      </el-button>
      <el-button 
        @click="getData()"
        size="large" 
        icon="Refresh" 
        type="primary">
        任务刷新
      </el-button>
    </div>
    <div class="eventList">
      <div class="statistics">
        <div class="copywritingTitle">共计{{total}}个AI任务</div>
      </div>
      <el-table :data="tableData" stripe  :header-cell-style="{backgroundColor: '#f3f6f9',color:'#333',height:'50px'}" style="width: 100%">
        <el-table-column prop="CreateTime" label="提交任务日期" width="180" />
        <el-table-column prop="FileName" label="文件名称" width="180" :show-overflow-tooltip="{ popperClass: 'custom-tooltip' }"/>
        <el-table-column prop="FileType" label="文件类型" width="180" />
        <el-table-column prop="OutFileType" label="输出文档类型" width="180" />
        <el-table-column prop="LangFrom" label="源语言" width="180" >
          <template #default="scope">
            <div>{{ scope.row.LangFrom === 'zh-CHS' ? '中文' : '英语' }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="LangTo" label="目标语言" width="180" >
          <template #default="scope">
            <div>{{ scope.row.LangTo === 'zh-CHS' ? '中文' : '英语' }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="" label=""/>
        <el-table-column label=""  width="200" fixed="right">
          <template #default="scope">
            <div v-if="(scope.row.Status === 1 || scope.row.Status === 2 || scope.row.Status === 3)">
              等待AI生成中
            </div>
            <div v-else-if="scope.row.Status === 5">
              <el-icon class="is-loading">
                <Loading />
              </el-icon>
              AI生成中
            </div>
            <div v-else-if="scope.row.Status === 4">
              <!-- <el-button size="mini" type="primary" @click="downloadFile(scope.row, 1)">下载原文件</el-button> -->
              <el-button size="mini" type="primary" @click="downloadFile(scope.row, 2)">下载文件</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.row.AutoID, scope.row)">删除</el-button>
            </div>
            <div v-else>
              AI生成失败
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination 
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" 
          :current-page=pageNum
          :page-size=pageSize
          background layout="prev, pager, next" :total="total" />
      </div>
    </div>
  </div>
  <documentTranslation :name="name" :loading="loading" v-model="dialogVisible" @closeDialog="closeDialog" @submit="submit"></documentTranslation>
  <answerDialog :answerForm="answerForm" v-model="answerDialog" @closeanswer="closeanswer"></answerDialog>
</template>

<script>
import { connrequest } from '../api/connrequest'
import { parseTime } from '../utils/index'
import documentTranslation from './components/documentTranslation.vue'
import answerDialog from './components/answerDialog.vue'
export default {
  components:{
    documentTranslation,
    answerDialog
  },
  data(){
    return {
      pageNum: 1,
      pageSize: 10,
      total: 0,
      functionalArea: [
        {name: '文档翻译'},
      ],
      tableData:[],
      name: '',
      dialogVisible: false,
      loading: false,
      timer: null,
      flag: false,
      answerDialog: false,
      answerForm: {}
    }
  },
  created(){
    this.getData()
  },
  beforeDestroy() {
    if(this.timer) { //如果定时器还在运行 或者直接关闭，不用判断
      clearInterval(this.timer); //关闭
    }
  },
  methods:{
    async getData(){
      const data = {
        Paging: {
          QueryPageNo: this.pageNum,
          QueryPageLength: this.pageSize
        },
        Filter:{
          // Status: 4,
          // Name: sessionStorage.getItem('Name')
        }
      }
      const res = await connrequest('GetTranslRecord', data)
      this.flag = false
      res.Data.map(item => {
        item.CreateTime = parseTime(item.CreateTime)
        // item.demand = this.extractContent(item.Question)
        if(item.Status === 0 || item.Status === 2){
          this.flag = true
        }
      })
      if(this.flag === false){
        window.clearInterval(this.timer);
      }
      this.tableData = res.Data
      this.total = res.Paging.TotalCount
    },
    search(){
      this.$message.info('该功能还在开发中')
    },
    handleSizeChange(){},
    handleCurrentChange(num){
      this.pageNum = num
      this.getData()
    },
    downloadFile(row){
      let name = row.FileName.split('.')[0]
      let url = `${window.location.protocol}//${window.location.host}/translate_output/${row.UUID}`
      let fileName = `${name}.${row.OutFileType}`;
      const anchor = document.createElement('a');
      anchor.href = url;
      anchor.download = fileName;
      anchor.click();
    },
    handleDelete(uuid){
      this.$confirm('删除后无法恢复，是否确认删除?', '删除任务', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const data = {
          Data:{
            AutoID: uuid
          }
        }
        const res = await connrequest('DelTranslRecord', data)
        if(res.Status.StatusCode === 0){
          this.$message.success('删除成功')
          this.getData()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });          
      });
    },
    async showDialog(name){
      if(name !== '文档翻译'){
        this.$message.info('该功能还在开发中')
        return
      }
      this.name = name
      this.dialogVisible = true
    },
    closeDialog(){
      this.dialogVisible = false
    },
    closeanswer(){
      this.answerDialog = false
    },  
    async submit(formData){
      this.getData()
      this.loading = false
      this.dialogVisible = false
      this.timer = window.setInterval(() => {
        this.getData();
      }, 6000);
    },
  }
}
</script>

<style lang="scss" scoped>
  .main{
    width: calc(100vw - 125px);
    height: calc(100vh - 60px);
    background: #fff;
    padding: 20px;
    margin: 10px;
    .functionalArea{
      margin-bottom: 20px;
      .el-button{
        margin-right: 20px;
      }
    }
    .eventList{
      height: calc(100vh - 175px);
      overflow-y: auto;
      border: 1px solid #ebeef5;
      .statistics{
        height: 65px;
        padding: 0 10px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .el-select{
          margin-right: 10px;
        }
      }
    }
    .pagination{
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
</style>